package com.guigu.msm.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.guigu.msm.service.MsmService;
import com.guigu.msm.utils.MsmSenCodeUtils;
import com.guigu.tms.exception.TmsException;
import com.guigu.tms.result.ResultCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName:MsmServiceImpl
 * @Description:
 * @Author:longtao
 * @Date:2021/8/6
 * @Version:1.0
 */
@Service
public class MsmServiceImpl implements MsmService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    //发送短信的方法

    @Override
    public Boolean send(String phone) {
        if (StringUtils.isBlank(phone)) {
            throw new TmsException(ResultCode.ERROR_CODE, "值不能为空!");
        }
        String incr=redisTemplate.opsForValue().get("incre:" + phone);
        if (!StringUtils.isBlank(incr)) {
            if (Long.valueOf(incr)>=3) {
                throw new TmsException(ResultCode.ERROR_CODE, "你发送验证码已超过三次,请明天再来!");
            }
        }


        if (!StringUtils.isBlank(redisTemplate.opsForValue().get(phone))) {
            throw new TmsException(ResultCode.ERROR_CODE, "请勿重复发送验证码!");
        }

        //生成随机数
        try {
            String s = RandomUtil.randomNumbers(6);
            MsmSenCodeUtils.sendCode(s, phone);
            redisTemplate.opsForValue().setIfAbsent(phone, s, 60 * 5, TimeUnit.SECONDS);
            redisTemplate.opsForValue().increment("incre:" + phone);
            redisTemplate.expire("incre:" + phone, 1, TimeUnit.DAYS);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new TmsException(ResultCode.ERROR_CODE, "短信验证码发送错误!");
        }
    }

}
